import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
import router from '@/router'
// 引入vuex-persistedstate数据持久化
import createVuexPersisted from 'vuex-persistedstate'
import emptyImage from '@/assets/Empty.png'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    emptyImage,
    menuIndex: [],
    switchTab: [],
    keepAliveList: []
  },
  getters: {
  },
  mutations: {
    pushMenuIndex (state, payload) {
      state.menuIndex.push(payload)
    },
    pushSwitchTab (state, payload) {
      state.switchTab.push(payload)
    },
    resSwitchTab (state) {
      state.switchTab = []
    },
    newSwitchTab (state, payload) {
      state.switchTab = [...payload]
    },
    spliceSwitchTab (state, payload) {
      state.switchTab.splice(payload[0], payload[1])
    },
    keepAliveListPush (state, payload) {
      state.keepAliveList.push(payload)
    },
    newKeepAliveList (state, payload) {
      state.keepAliveList = [...payload]
    },
    forEachDelKeepAliveList (state) {
      state.keepAliveList = Array.from(new Set(state.switchTab.filter(item => item?.root === true))).map(item => item.modelName)
    }
  },
  actions: {
    keepAliveListFn (fn, val) {
      if (!fn.state.keepAliveList.find(item => item === val)) fn.commit('keepAliveListPush', val)
    },
    removeTab (fn, val) {
      if (val.thisPath === val.path) {
        router.push('/dashboard')
      }
      const model = fn.state.switchTab.find(item => item.path === val.path)
      const tab = fn.state.switchTab.filter(item => item.path !== val.path)
      fn.commit('newSwitchTab', tab)
      if (model?.modelName !== undefined) {
        if (!fn.state.switchTab.find(item => item.modelName === model.modelName) || model.root) {
          const res = fn.state.keepAliveList.filter(item => item !== model.modelName)
          fn.commit('newKeepAliveList', res)
        }
      }
    }
  },
  modules: {
    user
  },
  plugins: [
    createVuexPersisted({
      reducer (val) {
        // 指定储存某个模块的数据
        return {
          user: val.user
        }
      }
    })
  ]
})
